var router = require('express').Router();
var util = require('util');
var EventProxy = require("eventproxy")
var async = require('async');

var Consts = require('../consts');
var resultJson = require('../result-json');
var Utils = require('../utils');
var logger = require('../models/logger');
var Message = require('../models/Message');
var User = require('../models/User');
var Course = require('../models/Course');

//添加交流
router.post('/add', function(req, res) {
	var message = req.body;
	message = JSON.stringify(message);
	message = message.replace(/\</g, '&lt;').replace(/\>/g, '&gt;').replace(/</g, '&lt;').replace(/>/g, '&lg;');
	message = JSON.parse(message);
	if (!message.media || !message.content || !message.to)
		return res.send(resultJson(3));
	message.from = message._user._id;
	message.create = new Date();
	new Message(message).save(function(err, msg) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		var item = JSON.parse(JSON.stringify(msg));
		User.findOne({
			_id: item.from
		}, {
			_id: 1,
			name: 1,
			photo: 1,
			username: 1
		}).exec(function(err, user) {
			if (err) {
				logger.error(err);
				return res.send(resultJson(2));
			}
			if (!user)
				user = {};

			item.userName = user.name || user.username;
			item.userPhoto = user.photo;
			res.send(resultJson(0, item));
		});

	})
});

//查看交流信息
router.post('/list', function(req, res) {
	var message = req.body;
	var to = message.to; //项目id
	var start = message.start || 0;
	var count = message.count || Consts.MAX;
	var proxy = new EventProxy();
	proxy.all("results", "count", function(results, count) {
		res.send(resultJson(0, {
			results: results,
			count: count
		}))
	})
	Message.find({
		to: to
	}).sort({
		_id: -1
	}).skip(start).limit(count).exec(function(err, messages) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		var result = [];
		messages = JSON.parse(JSON.stringify(messages));
		async.eachSeries(messages, function(item, cb) {
			User.findOne({
				_id: item.from
			}, {
				_id: 1,
				name: 1,
				photo: 1,
				username: 1
			}).exec(function(err, user) {
				if (err)
					cb(err);
				if (!user)
					user = {};
				item.userName = user.name || user.username;
				item.userPhoto = user.photo;
				result.push(item);
				cb();
			});
		}, function(err) {
			if (err) {
				logger.error(err);
				return res.send(resultJson(2));
			}
			proxy.emit("results", result);
		});
	});
	Message.count({
		to: to
	}).exec(function(err, num) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		proxy.emit("count", num);
	});
});

module.exports = router;